import os
import datetime

from django.conf import settings
from django.shortcuts import render, redirect, reverse
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.views.generic import ListView, View

from .models import Link, FileManager
from blog.views import CommonViewMixin

from fdfs_client.client import Fdfs_client, get_tracker_conf

MEDIA_PATH = settings.MEDIA_ROOT
MDEDITOR_CONFIGS = settings.MDEDITOR_CONFIGS['default']


class LinkListView(ListView, CommonViewMixin):
    queryset = Link.objects.filter(status=Link.STATUS_NORMAL)
    template_name = 'config/links.html'
    context_object_name = 'link_list'


def get_files(path):
    return os.listdir(path)


def get_path():
    # image floder check
    file_path = os.path.join(MEDIA_PATH, MDEDITOR_CONFIGS['image_folder'])
    base_file_path = MDEDITOR_CONFIGS['app_mdeditor_upload_base_path']
    date_file_path = os.path.join(base_file_path, file_path)
    date_path = datetime.datetime.now().strftime("%Y/%m/%d")
    return os.path.join(date_file_path, date_path)


def get_img_list():
    path = get_path()
    images = get_files(path)
    context = {
        'path': path,
        'images': images,
    }
    return context


def show(request):
    return render(request, 'show_imgs/show-imgs.html', context=get_img_list())


def delete_file(request, name):
    path = get_path()
    os.remove(path + '/' + name)
    return render(request, 'show_imgs/show-imgs.html', context=get_img_list())


class UploadFileList(ListView):
    queryset = FileManager.objects.order_by("-change_time")
    template_name = "upload/file-list.html"
    context_object_name = 'file_list'
    paginate_by = 15


class GetFileByTypeView(UploadFileList):

    def get_queryset(self):
        queryset = super().get_queryset()
        file_type = self.kwargs.get('file_type')
        return queryset.filter(file_type=file_type)


def upload(request):
    result = {"code": "", "data": [], "state": ""}
    if request.method == "POST":
        file = request.FILES.get("file")
        file_name = file.name

        client_path = os.path.join(
            os.path.dirname(__file__), "client.conf"
        )
        tracker_path = get_tracker_conf(client_path)

        file_size = file.size
        time_out = file_size // 1024 // 1024 // 5

        if tracker_path and time_out <= 0:
            time_out = tracker_path['timeout']

        try:
            client = Fdfs_client(client_path)
            client.timeout = time_out
            ret = client.upload_by_buffer(file.read(), file_ext_name=file_name.split('.')[-1])
        except Exception as e:
            result["code"] = 500
            result["state"] = str(e)
            result["data"].append(str(e))
        else:
            f = FileManager()
            f.file_name = file_name
            f.remote_name = ret.get("Remote file_id")
            f.upload_size = ret.get("Uploaded size")
            f.file_type = file_name.split('.')[-1].upper()
            f.upload_time = datetime.datetime.now()
            f.change_time = datetime.datetime.now()
            f.group_name = ret.get("Group name")
            f.storage_ip = ret.get("Storage IP")
            f.save()
            result["code"] = 200
            result["state"] = "上传成功"
            result["data"].append({
                "file_name": file_name,
                "file_size": f.upload_size,
                "file_id": f.id
            })
    else:
        result["code"] = 403
        result["state"] = "请求失败"
        result["data"].append("请求失败")
    print(result)
    return JsonResponse(result)


def upload_file_info(request, f_id):
    file = FileManager.objects.filter(id=f_id).first()

    if file:
        host = settings.FDFS_URL
        src = host + file.remote_name.replace("b'", "").replace("'", "")
        suffix = file.file_name.rsplit(".")[1].upper()
        image = ["JPG", "JPEG", "PNG", "GIF", 'BMP']
        video = ['WEBM', 'MP4', 'OGG', 'FLV', 'AAC', 'MOV', 'MKV', 'M3U8', 'MP3', 'FLAC']
        if suffix in image:
            label = "img"
        elif suffix in video:
            label = "video"
        else:
            label = "none"
    return render(request, "upload/file-info.html", locals())


def download(request):
    result = {"code": "", "data": [], "state": ""}
    id_list = request.GET.getlist("file")
    for id in id_list:
        file = FileManager.objects.filter(id=id).first()

        if file:
            client_path = os.path.join(
                os.path.dirname(__file__), "client.conf"
            )
            client = Fdfs_client(client_path)
            filename = file.file_name
            remote_name = file.remote_name.replace("b'", "").replace("'", "")
            with open(filename, "wb") as f:

                content = client.download_to_buffer(remote_name.encode())
                f.write(content["Content"])
            result["code"] = 200
            result["data"].append("下载完成")
            result["state"] = "下载完成"
        else:
            result["code"] = 400
            result["data"].append("id 为 %s的文件不存在" % id)
            result["state"] = "不完整下载"
            continue

    return JsonResponse(result)


def delete_upload_file(request, f_id):
    file = FileManager.objects.filter(id=f_id).first()
    if file:
        client_path = os.path.join(
            os.path.dirname(__file__), "client.conf"
        )
        result, file_remote_name, host = '', '', ''
        try:
            client = Fdfs_client(client_path)
            result, file_remote_name, host = client.delete_file(file.remote_name)
        except Exception as e:
            print(e)

        if result == 'Delete file successed.':
            file.delete()

    return redirect(reverse('blog:file-list'))
